package com.by.servlet;



import com.by.http.HttpRequest;
import com.by.http.HttpResponse;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ServletContainer {
    private Map<String, Servlet> servletMap = new HashMap<>();

    public void addServlet(String urlPattern, Servlet servlet) throws Exception {
        servlet.init();
        servletMap.put(urlPattern, servlet);
    }

    public void start(int port) throws Exception {
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server started on port " + port);

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> {
                try {
                    handleRequest(socket);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private void handleRequest(Socket socket) throws Exception {
        InputStream input = socket.getInputStream();
        OutputStream output = socket.getOutputStream();

        HttpRequest request = new HttpRequest(input);
        HttpResponse response = new HttpResponse(output);

        String uri = request.getUri();
        Servlet servlet = servletMap.get(uri);
        if (servlet != null) {
            servlet.service(request, response);
        } else {
            response.write("<h1>404 Not Found</h1>");
        }

        socket.close();
    }
}